const aldstat = require("./utils/ald-stat.js");
import util from "utils/util.js";
import p from "./utils/platform";
import api from "./common/api";
import NetWork from "./utils/network";
import TimController from "./utils/imLibs/index"
import Event from "./common/event"
import { systomModel } from "./utils/config";
import { getGioUserInfo } from "./common/gioHandler";

const cityMap = require('./utils/city')

require("./utils/push_sdk.js");
var gio = require("./utils/gio-minp/index.js").default;
var gioConfig = require("./gioConfig.js").default;
gio("setConfig", gioConfig);

wx.gio = gio;

// https://www.growingio.com/projects/nRbj2qdR/project-management/install_sdk

let optionsQuery = null;
let channel = "";
App({
  timControl: new TimController(new Event()), //im消息控制器实例
  gio,
  onLaunch: function (options) {
    console.log("###版本###", util.envVersion);
    console.log("###app options###",options)

    optionsQuery = options.query;

    if (options.query) {
      const query = options.query;
      let agentId = query.agentId || query.fromUserId;
      if (agentId) {
        this.globalData.agentId = agentId;
      }
      this.globalData.aldsrc = query.wxwork_userid || query.aldsrc || query.aid || query.q || query.gio_link_id;
      // wxwork_userid 优先级最高
      channel = query.channel;
    }

    this.globalData.path = options.path;
    this.globalData.scene = options.scene;
    this.globalData.shareTicket = options.shareTicket || '';

    // 二维码数据
    const queryScene = options.query.scene;

    //获取屏幕高度
    this.screenSize();
    this.appUpdate();

    this.globalData.systemPromise = this.initSystemInfo();
    this.globalData.loginPromise = new Promise((resolve, reject) => {
      NetWork.getInstance()
        .init()
        .then(() => {
          return this.parseQueryScene(queryScene)
        })
        .then((data) => {
          this.globalData.querySceneInfo = data
          return this.wxLogin()
        })
        .then((content) => {
          wx.nextTick(() => {
            this.getMemberPower();
            // this.initMemoryEvent();
          });
          
          resolve(content)
        })
    });
  },

  // 解析扫描二维码
  parseQueryScene(queryScene) {
    if (!queryScene) return Promise.resolve(null)
    return new Promise((resolve, reject) => {
      api.qrcodeShortToLong(queryScene, {}, ({ data }) => {
        let { content } = data;
        let result = null;
        if (content) {
          result = JSON.parse(content);
        }
  
        resolve(result)
      }, () => {
        resolve(null)
      });
    })
  },

  initMemoryEvent() {
    wx.onMemoryWarning(({level}) => {
      if (!util.isReleaseUrl) {
        wx.showToast({ icon: 'none', title: '内存警告~' + level, })
      }
    })
  },

  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          this.wechatLogin(res).then((content) => {
            const { wechatOpenid, wechatUnionid, wxMobile, nickname, city } = content.sessionUser.extProps;
            const { agentId, scene } = this.globalData

            // 向小神推上报用户openID
            wx.aldPushSendOpenid(wechatOpenid);
            // 绑定微信用户ID
            gio("identify", wechatOpenid, wechatUnionid);
            // 上传登录用户id
            gio("setUserId", content.sessionUser.id);

            getGioUserInfo().then((info) => {
              let params = {
                login_openid: wechatOpenid,
                userUnionid: wechatUnionid,
                phone: wxMobile,
                wechatName: nickname,
                city_ppl: city,
                inviteId_ppl: agentId,
                inviteScene_ppl: scene,

                ...info,
              }
              gio("setUser", params);
            })

            resolve(content);
          });
        },
        fail: (res) => {
        },
        complete(err) {
          try {
            gio("track", 'authCode', {
              "result_code": err.code,
              "result_msg": err.errMsg
            });
          } catch (error) {}
        }
      });
    })
  },

  initSystemInfo() {
    return new Promise((resolve, reject) => {
      wx.getSystemInfo({
        success: (res) => {
          let menuButtonObject = wx.getMenuButtonBoundingClientRect();
          let navTop = menuButtonObject.top;
          let navHeight =
            res.statusBarHeight + menuButtonObject.height + (menuButtonObject.top - res.statusBarHeight) * 2;
            // 防止意外
          if (navTop <= 0 || navHeight <= 0) {
            let modelKey = Object.keys(systomModel).find(v => {
              return res.model.toLowerCase().indexOf(v) > -1
            })
            let modelValue = modelKey ? systomModel[modelKey] : systomModel.default
            navTop = modelValue.navTop
            navHeight = modelValue.navHeight
          }

          this.globalData.navHeight = navHeight;
          this.globalData.navTop = navTop;

          this.globalData.windowHeight = res.windowHeight;
          this.globalData.deviceInfo = res;
          this.globalData.windowHeight = res.windowHeight;
          this.globalData.windowWidth = res.windowWidth;
          const isIOS = this.globalData.deviceInfo.isIOS = !!this.globalData.deviceInfo.system.match(/ios/i);
          const safeArea = res.safeArea || {};
          const safeAreaBottomHeight = res.screenHeight - safeArea.bottom
          if (isIOS && safeAreaBottomHeight > 0) {
            this.globalData.safeAreaBottomHeight = safeAreaBottomHeight / 2
          }
          wx.setStorageSync('systemInfo', {
            height: navHeight,
            top: navTop,
          })
          resolve(this.globalData);
        },
      });
    });
  },

  onShow(options) {
    // console.log("###app onshow###", options.query.bannerCode);
    this.globalData.testUserID = options.query.unionid
    this.globalData.bannerCode = options.query.bannerCode

    const query = options.query;
    this.globalData.aldsrc = query.wxwork_userid || query.aldsrc || query.aid || query.q || query.gio_link_id;

    switch (options.scene) {
      case 1037:
        if (!options.referrerInfo || !options.referrerInfo.extraData) {
          return
        }
        const extraData = options.referrerInfo.extraData;
        if (extraData.type == "trtc") {
          if (extraData.mustLogin) {
            this.globalData.mustLogin = extraData.mustLogin;
          }
        }
        break;
      case 1044:
        break;
    }
  },

  //授权登录
  wechatLogin: function (e) {
    var that = this;
    that.globalData.code = e.code;

    return new Promise((resolve, reject) => {
      const params = ["path", "scene"].reduce((pre, next) => {
        if (this.globalData[next]) {
          pre[next] = this.globalData[next];
        }
        return pre;
      }, {});
      console.log("###登录参数###", optionsQuery);

      let sourceUserId = this.globalData.agentId
      if (!sourceUserId && this.globalData.querySceneInfo) {
        sourceUserId = this.globalData.querySceneInfo.fromUserId || ''
      }
      this.getShareInfo().then((dataBody) => {
        let header = {
          sourceUserId,
          shareInfoJsonStr: JSON.stringify(dataBody),
          ...params,
          channel,
        };
        let aldsrc = optionsQuery.wxwork_userid ||
        optionsQuery.aldsrc ||
        optionsQuery.aid ||
        optionsQuery.q ||
        optionsQuery.gio_link_id
        
        if (!util.isReleaseUrl) {
          // header.aldsrc = 'JJKSD'
        } else if (aldsrc) {
          header.aldsrc = aldsrc
        }
        console.log("###登录参数header####", header);

        wx.request({
          url: `${util.domain}user/login/wechat`,
          method: "get",
          data: {
            code: e.code,
            miniName: "jjrjs",
          },
          header,
          success: function (res) {
            res.data.content = res.data.content || {};
            res.data.content.sessionUser = res.data.content.sessionUser || {};
            res.data.content.sessionUser.extProps = res.data.content.sessionUser.extProps || {};

            const sessionUser = res.data.content.sessionUser
            const extProps = sessionUser.extProps

            // 调试代码(新用户)
            // sessionUser.extProps.wechatUnionid = null
            // sessionUser.mobile = null

            console.log("###登录返回数据###", res);
            //在分享的时候需要
            that.globalData.isLogined = true;
            
            wx.setStorageSync("user", {
              nickname: extProps.nickname,
              wxHeadImg: extProps.wxHeadImg,
              wxMobile: extProps.wxMobile,
              unionid: extProps.wechatUnionid,
              openId: extProps.wechatOpenid,
            });
            that.globalData.sessionUser = sessionUser;
            that.globalData.loginUserInfo = res;

            const loginCity = sessionUser.extProps.loginCity
            if (loginCity) {
              that.globalData._wx_city = loginCity; //上次登录城市
              that.globalData.loginCity = loginCity; //ip城市
              let itemData = cityMap.cityObjs.find(item => item.city === loginCity) //ip城市
              if (itemData) {
                that.globalData.loginCityCode = itemData.code
              }
            }
            util.getToken(res.data.content.token);
            if (that.mobileReadyCallback) {
              that.mobileReadyCallback(res);
            }
            // 上传访客用户信息
            gio("setVisitor", {
              country: sessionUser.extProps.country,
              city: sessionUser.extProps.city,
              gender: sessionUser.extProps.gender,
              province: sessionUser.extProps.province
            });

            wx.aldstat.sendOpenid(extProps.wechatOpenid);
            resolve(res.data.content);
          },
          fail: function (res) {
            console.log('###登录失败###', res);
          },
          complete(err) {
            try {
              gio("track", 'authToken', {
                "wechat_nickname": err.data.content.sessionUser.extProps.nickname,
                "wechat_avatar": err.data.content.sessionUser.extProps.wxHeadImg,
                "phone": err.data.content.sessionUser.mobile,
                "token": err.data.content.token,
                "wechat_openid": err.data.content.sessionUser.extProps.wechatOpenid,
                "wechat_unionid": err.data.content.sessionUser.extProps.wechatUnionid,
                "result_msg": err.data.successMessage || err.data.content.msg,
                "result_code": err.data.content.code,
              });
            } catch (error) {}
          }
        });
      });
    });
  },

  getShareInfo() {
    return new Promise((resolve, reject) => {
      const res = wx.getSystemInfoSync()
      const version = res.SDKVersion
      if (this.globalData.shareTicket) {
        wx.getShareInfo({
          shareTicket: this.globalData.shareTicket,
          success: (res) => {
            resolve({iv: res.iv, encryptedData: res.encryptedData, cloudID: res.cloudID});
          },
          fail: (error) => {
            resolve(null);
          },
        });
      } else {
        if (this.compareVersion(version, '2.17.3') >= 0) {
          wx.getGroupEnterInfo({
            success(res) {
              resolve({iv: res.iv, encryptedData: res.encryptedData, cloudID: res.cloudID});
            },
            fail(error) {
              resolve(null);
            }
          })
        } else {
          resolve(null);
        }
      }
    });
  },

  //only user index
  globalData: {
    authorTodoList: [], //授权后的待办事项
    imStart: false, //im消息是否需要进入就开启（正式环境会忽略该参数）
    aldsrc: null,
    channel: null, //记录从哪儿扫码过来
    path: "", //进来时去的页面路径
    querySceneInfo: null, //通过二维码扫进来的 长转短 字符码解析对象
    offlineRedPaperFlag: 1, //地推红包  0：展示，1 不展示
    loginPromise: null, //登录的promise
    systemPromise: null, //初始化设备系统信息的promise
    isLogined: false,
    code: "",
    windowHeight: 0,
    windowWidth: 0,
    safeAreaBottomHeight: 0, //iphone11 底部提升高度
    height: 0,
    userInfo: null,
    scene: 0,
    deviceInfo: {},
    loginUserInfo: {},
    sessionUser: {}, //登录后的用户数据
    afterMobileAuthorCallBack: "", //手机授权后的回调
    needShowEdit: 0,
    mustLogin: false, //是否强制登录
    gatherHouseSearchValue: "", //房源搬家的搜索关键字
    newHouseSearchValue: "", //新房楼盘的搜索关键字
    vieSearchValue: "", //抢房的搜索关键字
    homeHouseSearchValue: "", //home我的房源 搜索关键字
    inputTextValuePage: "", //inputTextValue.page 输入框页面的保存值
    mapTabStatusIndex: 0, //地图周边关键词的当前索引值
    newUser: false, // 新人提交审核后的弹窗
    isFirstShop: false, // 是否次首次从个人的店铺点进来
    indexPage: null, //首页实例
    bannerComponent: null, //banner实例
    houseShareBannerInfo: {}, //房源海报分享数据
    testAvatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLibWZaJnsQQpBNTmbrWEtNmA81pRvzTHjolyT5avbMclcAXuxhR3gfNYnf4Bz1icJqU1Bz5iamkw8LQ/132",
    defaultHouseUrl: "https://api.shulanfd.com/aist-filesvr-web/api/files/221b0f07dec7412aa253550d66375744",
    defaultShareImgUrl: "https://api.shulanfd.com/aist-filesvr-web/api/files/dbb4ef49df534cc89c0575406863e17d",
    cdnResourceUrl: "https://shulan-prod.oss-cn-shanghai.aliyuncs.com/static/jjrjs/resource/",
    shareTicket: "", //分享到群的参数
    agentId: "", //分享人ID
    vrHouseInfo: {}, //vr房源详情
    radarInfo: {}, //雷达详情
    addApp: false, //引导添加到小程序永久关闭提示
    searchType: "", //搜索类型，热词 历史 手动
    haveMoveHouse: false, //  是否成功扫码搬家过 
    hold: false, //挽留 1、没有任何操作；2、没有扫任何码；3、扫码失败
    posterTmp: {}, // 当前选择的海报模板,
    localReported: false, //本次登录上报过坐标
    isShowMemberCenter: false, //是否显示敏感信息
    testUserID: "",// im消息用
    _wx_city: "上海市",
    loginCity: "上海市", //ip城市
    loginCityCode: "", //ip城市code
    lastPage: '', //记录上一次的页面
    needShowDetainment: false, //进入首页是否需要展示挽留（未登录过web端）
    bannerCode: null, //分享banner页
    pageFrom: '', // 页面来源 (目前是im聊天对话也专用)
  },
  eventBus: new Event(),

  isOldUser() {
    const { wxMobile, nickname } = this.globalData.sessionUser.extProps
    return wxMobile && nickname;
  },

  resetQueryScene() {
    this.globalData.querySceneInfo = null
  },
  updateSessionUser(data) {
    this.globalData.sessionUser = data;
    let loginUserInfo = getApp().globalData.loginUserInfo;

    if (loginUserInfo) {
      loginUserInfo.data.content.sessionUser = this.globalData.sessionUser;
      this.globalData.loginPromise = Promise.resolve(loginUserInfo.data.content)
    }
  },

  // 刷新session信息
  refreshSession() {
    api.getSessionInfo(null, ({data}) => {
      let loginUserInfo = getApp().globalData.loginUserInfo;

      this.globalData.sessionUser = data.content;
      loginUserInfo.data.content.sessionUser = this.globalData.sessionUser;
      this.globalData.loginPromise = Promise.resolve(loginUserInfo.data.content)
    })
  },

  assignSession(data) {
    Object.assign(this.globalData.sessionUser, data)
  },
  
  // 发布用户信息更新
  publishSessionUserChange() {
    this.eventBus.trigger("update_sessionuser");
  },

  screenSize: function () {
    var that = this;
    wx.setStorageSync("isCon", "1");
    wx.setStorageSync("currentStatus", 1);
    wx.setStorageSync("isChoseCity", false);
    wx.setStorageSync("boole", true);
  },

  appUpdate() {
    //检查小程序冷启动时是否有更新
    if (p.canIUse("getUpdateManager")) {
      const updateManager = p.getUpdateManager();
      if (updateManager && updateManager.onUpdateReady) {
        updateManager.onUpdateReady(function () {
          // 强制升级
          updateManager.applyUpdate();
        });
      }
    }
  },

  getCurrentStatusName() {
    let i = wx.getStorageSync("currentStatus");
    if (i == 1) return "SALES";
    if (i == 2) return "RENT";
    if (i == 3) return "NEWHOUSE";
    return "SALES";
  },
  // 获取用户的会员信息
  getMemberPower() {
    api.getMemberPower({}, (res) => {
      wx.setStorageSync("memberInfo", res.data.content.rows);
    });
  },

  checkHouses(a) {
    if (this.globalData.checkHouses) {
      return Promise.resolve()
    }
    return new Promise((resolve, reject) => {
      api.checkHouses({}, (res) => {
        this.globalData.checkHouses = res.data.content;
        resolve(res);
      });
    });
  },

  checkPcLogin() {
    if (this.globalData.checkPcLogin) {
      return Promise.resolve(true)
    }
    
    return new Promise((resolve, reject) => {
      api.checkPcLogin({}, (res) => {
        this.globalData.checkPcLogin = res.data.content;
        resolve(this.globalData.checkPcLogin);
      });
    });
  },

  checkMobileHou(a) {
    if (this.globalData.checkMobileHou) {
      return Promise.resolve()
    }
    
    return new Promise((resolve, reject) => {
      api.checkMobileHou({}, (res) => {
        this.globalData.haveMoveHouse = res.data.content;
        resolve(res);
      });
    });
  },

  // 确保手机号已经授权(bool是否自定义未登录后的动作)
  mobileLogin(bool, title, route=true) {
    let queryStr = title ? `?title=${title}` : ''

    return this.globalData.loginPromise.then(() => {
        let mobile = this.globalData.sessionUser.mobile;
        let userInfo = wx.getStorageSync("user");
        if (mobile && userInfo.nickname && userInfo.wxHeadImg && userInfo.unionid) {
          return Promise.resolve(mobile);
        }

        if (!bool) {
          if(route){
            p.navigateTo({
              url: "/pages/startPage/startPage" + queryStr,
            });
          }else {
            p.redirectTo({
              url: "/pages/startPage/startPage" + queryStr,
            });
          }
        }
        return Promise.reject();
      })
  },

  appGotoNextPage(fn) {
    if (!fn && !this.globalData.afterMobileAuthorCallBack) {
      wx.redirectTo({
        url: "/pages/index/index",
      });
      return;
    }

    if (fn) {
      fn();
    } else {
      if (this.globalData.afterMobileAuthorCallBack) {
        this.globalData.afterMobileAuthorCallBack();
      }
    }
    this.globalData.afterMobileAuthorCallBack = null;
  },

  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
    return 0
  }
  

});
